package swe.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import swe.user.User;
import swe.user.UserDAO;
import swe.user.UserManager;

/**
 * Servlet implementation class login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("bluplplapsdfasd");
		HttpSession session = request.getSession();
		session.invalidate();
		response.sendRedirect("/buyallthestuff/index.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String nickname = (String) request.getParameter("nickname");
		String passwd = (String) request.getParameter("password");
		
		UserManager um = (UserManager) getServletContext().getAttribute("uManager");
		
			
		try {
			if(um.login(nickname, passwd)) {
				response.sendRedirect("/buyallthestuff/index.jsp");
				HttpSession session = request.getSession(true);
				User user = null;
				for(User u : um.getUserList()) {
					if(u.getUserName().equals(nickname)){
						user = u;
					}
				}
				session.setAttribute("User", user);
				session.setAttribute("isLoggedIn", Boolean.TRUE);
			} else {
				response.sendRedirect("/buyallthestuff/index.jsp");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
